<script setup lang='ts' name="personnel-organizational">
import type { VxeGridInstance, VxeGridListeners, VxeTableEvents, VxeTableInstance } from 'vxe-table'

import { departmentList, getOrganizationListByOrgId } from '@fl/api/iam-api'
import ButtonItem from '@fl/components/button-item.vue'
import { ElButton, ElCard, ElTree } from 'element-plus'
import { useRouter } from 'vue-router'

import type { IRowV0 } from './types'

import { TextDict, TypeDict } from '../constant'
import { useTable as useTable2 } from '../hooks/use-table'
import resetCodeBox from './component/resetCodeBox.vue'
import { useForm } from './hooks/use-form'
import { useTable } from './hooks/use-table'

const route = useRoute()

const { go, push } = useRouter()
const id = route.query.id as string
const enterpriseObjectID = route.query.enterpriseObjectID as string
const catTypeId = route.query.catTypeId as string

const isTrue = ref(true)
const router = useRouter()
const { btns, gridOptions } = useTable()
const { arrayToTree } = useTable2()
const { form, schema } = useForm()
const tempPagingStrat = ref(0)
const tempPagingEnd = ref(10)
tempPagingEnd.value = tempPagingStrat.value + 10
const tableRef = ref<VxeTableInstance<IRowV0>>()

const showaddDialog = ref(false)

const xGrid = ref<VxeGridInstance<IRowV0>>()

const treeData = ref<any>([])

const resetCodeVisible = ref(false)
const resetCodeUserId = ref('')
const resetCodeLoginName = ref('')

const defaultProps = {
    children: 'children',
    label: 'deptName',
}

form.value.userId = id
const treeRef = ref<InstanceType<typeof ElTree>>()

const gridEvents: VxeGridListeners<IRowV0> = {
    pageChange({ currentPage, pageSize }) {
        if (gridOptions.pagerConfig) {
            gridOptions.pagerConfig.currentPage = currentPage
            gridOptions.pagerConfig.pageSize = pageSize
        }
        getData()
    },
}

// 右侧人员数据
// 首次+重置：用userId即企业号查；点击树：userId置为空，用deptId查
function getData() {
    gridOptions.loading = true
    getOrganizationListByOrgId({
        ...form.value,
        page: gridOptions.pagerConfig.currentPage,
        size: gridOptions.pagerConfig.pageSize,
    }).then((res) => {
        console.log('data res', res)
        gridOptions.data = res.rows
        gridOptions.pagerConfig.total = res.total
        gridOptions.loading = false
    })
}

// 点击机构树
function handleNodeClick(data: any) {
    console.log('handleNodeClick', data)
    form.value.deptId = data.deptId
    form.value.userId = ''
    console.log('点击data', data)
    getData()
}

// 组织机构树
function getTreeData() {
    departmentList({ enterprise: id }).then((res) => {
        console.log('tree res', res)
        treeData.value = arrayToTree(res.data, 'parentId', 'deptId')
        console.log('tree data', treeData.value)
        getData()
    })
}
getTreeData()

function reset() {
    form.value = {
        deptId: '',
        phonenumber: '',
        userId: id,
        userName: '',
    }
    getData()
}

function doAction(item: any, row: any) {
    // 编辑人员
    if (item.value === 'edit')
        router.push({ path: '/business-management/personnel-organizational/addPeople', query: { enterpriseObjectID: row.enterpriseObjectID, userId: id, uuId: row.uuid, catTypeId } })
    else if (item.value === 'resetPwd') {
        resetPwd(row)
    }
}

// 新增人员
function doAdd() {
    const deptId = form.value.deptId || treeData.value[0]?.deptId
    console.log('新增', form.value, deptId)
    push(`/business-management/personnel-organizational/addPeople?userId=${id}&deptId=${deptId}&enterpriseObjectID=${enterpriseObjectID}&catTypeId=${catTypeId}`)
}

// // 批量启用
// function multipleEnable() {
//     const $table = xGrid.value
//     if ($table) {
//         const records = $table.getCheckboxRecords()
//         console.log('records', records)
//     }
// }

// // 批量禁用
// function multipleDisable() {

// }

// 重置密码
function resetPwd(row: any) {
    console.log('row', row)
    resetCodeVisible.value = true
    resetCodeUserId.value = String(row.userId)
    resetCodeLoginName.value = row.loginName
}

const selectAllChangeEvent: VxeTableEvents.CheckboxAll<IRowV0> = ({ checked }) => {
    const $table = tableRef.value
    if ($table) {
        const records = $table.getCheckboxRecords()
        console.log(checked ? '所有勾选事件' : '所有取消事件', records)
    }
}

const selectChangeEvent: VxeTableEvents.CheckboxChange<IRowV0> = ({ checked }) => {
    const $table = tableRef.value
    if ($table) {
        const records = $table.getCheckboxRecords()
        console.log(checked ? '勾选事件' : '取消事件', records)
    }
}

function filterNode(value: string, data: any) {
    if (!value)
        return true
    return data.label.includes(value)
}

// 部门管理
function createSection() {
    router.push(`/business-management/department-management?deptId=${id}`)
}

function goback() {
    go(-1)
}
</script>

<template>
    <div flex
         justify-between
    >
        <ElCard v-show="!showaddDialog"
                style="width:20%"
        >
            <div flex>
                <ElButton class="mb-20"
                          @click="goback"
                >
                    返回企业列表
                </ElButton>

                <!-- <ElInput v-model="filterText" /> -->

                <ElButton ml-6
                          class="el-button el-button--primary el-button--default"
                          @click="createSection"
                >
                    部门管理
                </ElButton>
            </div>

            <ElTree ref="treeRef"
                    style="max-width: 600px"
                    :data="treeData"
                    :props="defaultProps"
                    :filter-node-method="filterNode"
                    :default-expand-all="isTrue"
                    :highlight-current="isTrue"
                    :expand-on-click-node="isTrue"
                    @node-click="handleNodeClick($event)"
            />
        </ElCard>

        <ElCard v-show="!showaddDialog"
                style="width:80%"
                ml-20
        >
            <ElCard class="mb-20">
                <PlusForm v-model="form"
                          :row-props="{ gutter: 20 }"
                          :columns="schema"
                          :col-props="{
                              span: 16,
                          }"
                          justify-between
                          style="display: flex;"
                >
                    <template #footer>
                        <div class="ml-auto">
                            <ElButton type="primary"
                                      @click="getData"
                            >
                                查询
                            </ElButton>

                            <ElButton @click="reset">
                                重置
                            </ElButton>
                        </div>
                    </template>
                </PlusForm>
            </ElCard>

            <ElCard>
                <div class="mb-20">
                    <ElButton type="primary"
                              @click="doAdd"
                    >
                        +新增人员
                    </ElButton>

                    <!-- <ElButton @click="multipleEnable">
                        批量启用
                    </ElButton>

                    <ElButton @click="multipleDisable">
                        批量停用
                    </ElButton> -->
                </div>
                <!-- 列表 -->
                <vxe-grid ref="xGrid"
                          v-bind="gridOptions"
                          v-on="gridEvents"
                          @checkbox-all="selectAllChangeEvent"
                          @checkbox-change="selectChangeEvent"
                >
                    >
                    <template #status="{ row }">
                        <div style="cursor: pointer;">
                            <ElTag :type="TypeDict[row.status]">
                                {{ TextDict[row.status] }}
                            </ElTag>
                        </div>
                    </template>

                    <template #operate="{ row }">
                        <ButtonItem :btns="btns"
                                    @btn-click="doAction($event, row)"
                        />
                    </template>
                </vxe-grid>
            </ElCard>
        </ElCard>
    </div>

    <resetCodeBox v-model:visible="resetCodeVisible"
                  v-model:userid="resetCodeUserId"
                  v-model:loginname="resetCodeLoginName"
                  :catTypeIdStr="catTypeId"
    />
</template>

<style lang="scss" scoped>
:deep(.el-row) {
    width: 80%;
}
</style>
